package com.se.controller;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.se.domain.dto.page.PageDTO;
import com.se.domain.mysql.ActivityDO;
import com.se.domain.request.param.ListApplyUserParam;
import com.se.domain.vo.*;
import com.se.exception.ResultException;
import com.se.global.AuthHeaderRequestWrapper;
import com.se.service.ActStaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

@RestController
@Slf4j
public class ActStaController {
    @Autowired
    ActStaService actStaService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping("/must/act/apply/list")
    public ResultVO<ApplyUserListVO> listApplyUser(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestBody @Validated ListApplyUserParam param
    ) throws ResultException {
        List<ApplyVO> voList = actStaService.listApplyUser(param, userId);
        ApplyUserListVO vo = new ApplyUserListVO();
        vo.setList(voList);
        vo.setPage(new PageDTO(param.getPage().getPage(), voList.size()));

        return ResultVO.ok(vo);
    }

    @PostMapping("/must/act/apply/info")
    public ResultVO<ApplyVO> getApplyInfo(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestParam Long actId,
            @RequestParam Long applyId
    ) throws ResultException {
        ApplyVO applyVO = actStaService.getApplyInfo(actId, applyId, userId);
        return ResultVO.ok(applyVO);
    }

    @PostMapping("/must/act/apply/q")
    public ResultVO<ApplyQRecordVO> getQSta(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestParam Long actId,
            @RequestParam Long qId
    ) throws ResultException {

        ApplyQRecordVO vo = actStaService.listApplyQRecord(actId, qId, userId);

        return ResultVO.ok(vo);
    }

    @GetMapping("/no/act/apply/excel")
    public void applyExcel(
            @RequestParam String data,
            @RequestParam Long userId,
            HttpServletResponse response
    ) throws Exception {
        String privateKey = redisTemplate.opsForValue().get(userId+"-privateKey");
        RSA rsa = new RSA(privateKey, null);
        String decryptStr = rsa.decryptStr(data, KeyType.PrivateKey);
        JSONObject jsonObject = JSONUtil.parseObj(decryptStr);

        userId = jsonObject.getLong("userId");
        Long actId = jsonObject.getLong("actId");
        if(userId == null || actId == null){
            throw new Exception();
        }
        // 创建一个工作簿和工作表
        Pair<ActivityDO, Workbook> pair = actStaService.generateApplyExcel(actId, userId);
        Workbook workbook = pair.getValue();
        ActivityDO activityDO = pair.getKey();

        String filename = activityDO.getTitle()+"_活动报名记录.xlsx";

        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        // response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(filename,"UTF-8"));
        workbook.write(response.getOutputStream());
        ((SXSSFWorkbook)workbook).dispose();
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        workbook.write(outputStream);
//        outputStream.close();
//
//        // 设置HTTP响应头，将Excel文件作为响应返回
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
//        headers.setContentDispositionFormData("attachment", "sample.xlsx");
//        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
//
//        return ResponseEntity.ok()
//                .headers(headers)
//                .body(outputStream.toByteArray());
    }
}
